{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table class=\"ee-notebook-buttons\" align=\"left\">\n",
    "    <td><a target=\"_blank\"  href=\"https://github.com/giswqs/geemap/tree/master/tutorials/Image/04_math_operations.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n",
    "    <td><a target=\"_blank\"  href=\"https://nbviewer.jupyter.org/github/giswqs/geemap/blob/master/tutorials/Image/04_math_operations.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n",
    "    <td><a target=\"_blank\"  href=\"https://colab.research.google.com/github/giswqs/geemap/blob/master/tutorials/Image/04_math_operations.ipynb\"><img width=26px src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Mathematical operations\n",
    "Earth Engine supports many basic mathematical operators. They share some common features. Earth Engine performs math operations per pixel. When an operator is applied to an image, it's applied to each unmasked pixel of each band. In the case of operations on two images, the operation is only applied at the locations where pixels in both images are unmasked. Earth Engine automatically matches bands between images. When an operator is applied to two images, the images are expected to have the same number of bands so they can be matched pairwise. However, if one of the images has only a single band, it is matched with all of the bands in the other image, essentially replicating that band enough times to match the other image."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Install Earth Engine API and geemap\n",
    "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n",
    "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n",
    "\n",
    "**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Installs geemap package\n",
    "import subprocess\n",
    "\n",
    "try:\n",
    "    import geemap\n",
    "except ImportError:\n",
    "    print('geemap package not installed. Installing ...')\n",
    "    subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n",
    "\n",
    "# Checks whether this notebook is running on Google Colab\n",
    "try:\n",
    "    import google.colab\n",
    "    import geemap.eefolium as emap\n",
    "except:\n",
    "    import geemap as emap\n",
    "\n",
    "# Authenticates and initializes Earth Engine\n",
    "import ee\n",
    "\n",
    "try:\n",
    "    ee.Initialize()\n",
    "except Exception as e:\n",
    "    ee.Authenticate()\n",
    "    ee.Initialize()  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create an interactive map \n",
    "The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = emap.Map(center=[40,-100], zoom=4)\n",
    "Map.add_basemap('ROADMAP') # Add Google Map\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add Earth Engine Python script "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a simple example, consider the task of creating the Normalized Difference Vegetation Index (NDVI) using Landsat imagery:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load two 5-year Landsat 7 composites.\n",
    "landsat1999 = ee.Image('LANDSAT/LE7_TOA_5YEAR/1999_2003')\n",
    "landsat2008 = ee.Image('LANDSAT/LE7_TOA_5YEAR/2008_2012')\n",
    "\n",
    "# Compute NDVI the hard way.\n",
    "ndvi1999 = landsat1999.select('B4').subtract(landsat1999.select('B3')) \\\n",
    "               .divide(landsat1999.select('B4').add(landsat1999.select('B3')))\n",
    "\n",
    "# Compute NDVI the easy way.\n",
    "ndvi2008 = landsat2008.normalizedDifference(['B4', 'B3'])\n",
    "\n",
    "# A nice NDVI palette.\n",
    "palette = ['#d73027', '#f46d43', '#fdae61', '#fee08b', '#d9ef8b', '#a6d96a', '#66bd63', '#1a9850']\n",
    "\n",
    "Map.addLayer(landsat1999, {'bands': ['B4', 'B3', 'B2']}, 'Landsat 1999')\n",
    "Map.addLayer(landsat2008, {'bands': ['B4', 'B3', 'B2']}, 'Landsat 2008')\n",
    "Map.addLayer(ndvi1999, {'palette': palette}, 'NDVI 1999')\n",
    "Map.addLayer(ndvi2008, {'palette': palette}, 'NDVI 2008')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As shown in the previous example, math operators perform basic arithmetic operations on image bands. The normalized difference operation is so common in remote sensing, Earth Engine provides a shortcut method, as shown in the second part of the example. Subtracting the images in this example results in a “change vector” for each pixel. Bands are matched automatically to perform the difference:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute the multi-band difference image.\n",
    "diff = landsat2008.subtract(landsat1999)\n",
    "Map.addLayer(diff,\n",
    "             {'bands': ['B4', 'B3', 'B2'], 'min': -32, 'max': 32},\n",
    "             'difference')\n",
    "\n",
    "# Compute the squared difference in each band.\n",
    "squaredDifference = diff.pow(2)\n",
    "Map.addLayer(squaredDifference,\n",
    "             {'bands': ['B4', 'B3', 'B2'], 'max': 1000},\n",
    "             'squared diff.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the second part of this example, the squared difference is computed using `image.pow(2)`. For the complete list of mathematical operators handling basic arithmetic, trigonometry, exponentiation, rounding, casting, bitwise operations and more, see the API documentation (in the **Docs** tab of the [Earth Engine Code Editor](https://code.earthengine.google.com/))."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.addLayerControl()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Expressions\n",
    "To implement more complex mathematical expressions, it may be more convenient to use `image.expression()`, which parses a text representation of a math operation. The following example uses `expression()` to compute the Enhanced Vegetation Index (EVI):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = emap.Map(center=[40, -100], zoom=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load a Landsat 8 image.\n",
    "image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318')\n",
    "\n",
    "# Compute the EVI using an expression.\n",
    "evi = image.expression(\n",
    "    '2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {\n",
    "      'NIR': image.select('B5'),\n",
    "      'RED': image.select('B4'),\n",
    "      'BLUE': image.select('B2')\n",
    "})\n",
    "\n",
    "Map.centerObject(image, 9)\n",
    "Map.addLayer(image, {'bands': ['B5', 'B4', 'B3']}, 'Landsat 8')\n",
    "Map.addLayer(evi, {'min': -1, 'max': 1, 'palette': ['FF0000', '00FF00']}, 'EVI')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Display Earth Engine data layers "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.addLayerControl()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Observe that the first argument to expression is the textual representation of the math operation, the second argument is a dictionary where the keys are variable names used in the expression and the values are the image bands to which the variables should be mapped. Bands in the image may be referred to as `b(\"band name\")` or `b(index)`, for example `b(0)`, instead of providing the dictionary. Note that division functions as it does in Python: dividing two integers results in an integer. For example `10 / 20 = 0`. To change this behavior, multiply one of the operands by `1.0: 10 * 1.0 / 20 = 0.5`. Supported expression operators are listed in the following table.\n",
    "\n",
    "![](https://i.imgur.com/TyXM4s9.png)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
